using System;
using System.Diagnostics;
using System.ServiceModel;
using System.Threading;
using System.Reflection;
using System.Windows.Forms;

using Microsoft.Services.TfsAlert.Core;
using Microsoft.Services.TfsAlert.Forms;
using Microsoft.Services.TfsAlert.AppCode;


namespace Microsoft.Services.TfsAlert
{
    static class TfsAlert
    {
        public static ServiceHost ServiceHost = null;

        //      [STAThread]
        static void Main()
        {
            Mutex _applicationInstance = null;
            bool _isFirstInstance = true;


            try
            {
                _applicationInstance = new Mutex( true, "TfsAlert", out _isFirstInstance );

                if ( !_isFirstInstance )
                {
                    MessageBox.Show( "Instance Already running" );
                    return;
                }
                ApplicationHelpers applicationHelpers = new ApplicationHelpers();

                BasicHttpBinding basicHttpBinding = new BasicHttpBinding();

                TfsAlert.ServiceHost = new ServiceHost( typeof( NotificationReciever ), applicationHelpers.BuildFullAddress() );
                TfsAlert.ServiceHost.AddServiceEndpoint( typeof( INotificationReciever ), basicHttpBinding, applicationHelpers.BuildFullAddress() );
                TfsAlert.ServiceHost.Open();

                Application.EnableVisualStyles();
                Application.SetCompatibleTextRenderingDefault( false );
                Application.Run( new main() );
                _applicationInstance.Close(); //close the mutex
            }

            catch ( System.ServiceModel.CommunicationException ex )
            {
                if ( TfsAlert.ServiceHost != null )
                    TfsAlert.ServiceHost.Abort();

                Trace.Write( "Communication Exception: " + ex.Message );
            }

            catch ( Exception ex )
            {
                if ( TfsAlert.ServiceHost != null )
                    TfsAlert.ServiceHost.Abort();

                Trace.Write( "Global Exception: " + ex.Message );
            }
        }
    }
}